package com.jiankangjin.weixinchannel.services.impl;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jiankangjin.httpclient.HttpClient;
import com.jiankangjin.httpclient.PropertiesLoader;
import com.jiankangjin.weixinchannel.config.WeixinConfig;
import com.jiankangjin.weixinchannel.services.RefundService;
import com.jiankangjin.weixinchannel.util.MD5Util;
import com.jiankangjin.weixinchannel.util.Sha1Util;
import com.jiankangjin.weixinchannel.util.XMLUtil;
import com.jiankangjin.weixinchannel.vo.RefundVo;

/**
 * 支付宝所有类型版本退款方法实现
 */
public class RefundServiceImpl implements RefundService {
	private static final transient Log logger = LogFactory.getLog(RefundServiceImpl.class);
	
	/**
	 * 对应微信接口：	https://api.mch.weixin.qq.com/secapi/pay/refund	
	 */
	@Override
	public RefundVo barcode_V0_0_1(String pay_ssn_id, String order_id,
			String total_fee, String pay_chnl_seq, String refund_fee,
			String currency, String expand_json) {
		RefundVo refundVo = new RefundVo();
		try {
			InputStream instream = PropertiesLoader.class.getClassLoader().getResourceAsStream(WeixinConfig.MCH_ID+".p12");
			HttpClient httpClient = HttpClient.getInstance(instream, "PKCS12", WeixinConfig.MCH_ID);//证书文件流 证书类型 证书密码
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("appid", WeixinConfig.APP_ID);
			params.put("mch_id", WeixinConfig.MCH_ID);//商户号
			params.put("sub_mch_id", "");//子商户号
			params.put("device_info", "");//设备号
			params.put("nonce_str", Sha1Util.getNonceStr());// 随机串
			params.put("transaction_id", pay_chnl_seq);//微信订单号
			params.put("out_trade_no", pay_ssn_id);//商户订单号
			params.put("out_refund_no", System.currentTimeMillis());//商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔
			params.put("total_fee", "1");
			params.put("refund_fee", "1");
			params.put("op_user_id", WeixinConfig.MCH_ID);
			Map<String, Object> sPara = MD5Util.MD5Encode(params, "utf8");
			String xmlStr = XMLUtil.toXMLstr(sPara);
			String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
			logger.info("调微信统退款申请接口:" + xmlStr);
			String responseStr = httpClient.doPost(url, xmlStr.getBytes(), "gbk");
			//加上xml头,不加解析有编码的问题.
			responseStr = "<?xml version=\"1.0\" encoding=\"UTF8\"?>\n" + responseStr;
			Map<String, String> returnMap = XMLUtil.doXMLParse(responseStr);
	    	logger.info("微信统退款申请接口返回:"+returnMap);
	    	
	    	if ("SUCCESS".equals(returnMap.get("return_code"))) {
	    		if ("SUCCESS".equals(returnMap.get("result_code"))) {
	    			refundVo.setPay_ssn_id(pay_ssn_id);
	    			refundVo.setPay_chnl_seq(pay_chnl_seq);
	    			refundVo.setRefund_fee(refund_fee);
	    	    	refundVo.setResp_status("0000");
	    	    	refundVo.setResp_msg("返回成功");
	    			refundVo.setRefund_status("1002");
	    			refundVo.setRefund_msg("退款成功");
	    	    	refundVo.setSign("weixinChannel_refund_sign");
	    	    	return refundVo;
				}
			} else {
		    	refundVo.setResp_status("0000");
		    	refundVo.setResp_msg("返回成功");
	    		refundVo.setRefund_status("0042");//调用失败，退款失败
	    		refundVo.setRefund_msg(returnMap.get("err_code_des"));//调用失败的原因消息
			}
	    	refundVo.setResp_status("0000");
	    	refundVo.setResp_msg("返回成功");
			refundVo.setRefund_status("0042");
			refundVo.setRefund_msg("退款失败");
	    	return refundVo;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
    	refundVo.setResp_status("9999");
    	refundVo.setResp_msg("系统报错");
		return refundVo;
	}
	/*
	 * {result_code=FAIL, 
	 * sign=E9A711E0E79FDC77C4A52E76E73D10A3, 
	 * mch_id=10017474, 
	 * err_code=TRADE_STATE_ERROR, 
	 * err_code_des=订单状态错误, 
	 * sub_mch_id=, 
	 * return_msg=OK, 
	 * appid=wxcec8863ae602c67c, 
	 * nonce_str=GYGswmpuIyN1F2D6, 
	 * return_code=SUCCESS}
	 * 
	 * {refund_id=2003810706201410100000137807, 
	 * refund_fee=1, 
	 * coupon_refund_fee=0, 
	 * refund_channel=,
	 * return_msg=OK, 
	 * appid=wxcec8863ae602c67c, 
	 * nonce_str=1N7NKjHeHTcBcXqC, 
	 * out_trade_no=20141009162628577-0000042ZJh8W4X, 
	 * out_refund_no=20141009162628577-0000042ZJh8W4X, 
	 * transaction_id=1003810706201410090005300615, 
	 * sign=D954526ABFE161A0A012297B090EB133, 
	 * result_code=SUCCESS, 
	 * mch_id=10017474, 
	 * sub_mch_id=, 
	 * return_code=SUCCESS}
	 */

	/**
	 * 
	 */
	@Override
	public RefundVo public_V2(String pay_ssn_id, String order_id,
			String total_fee, String pay_chnl_seq, String refund_fee,
			String currency, String expand_json) {
		RefundVo refundVo = new RefundVo();
		refundVo.setRefund_status("0042");
		refundVo.setRefund_msg("退款失败");
		refundVo.setResp_msg("V2版公众号支付不提供退款");
		return refundVo;
	}

	/**
	 * @throws IOException 
	 * 
	 */
	@Override
	public RefundVo public_V3(String pay_ssn_id, String order_id,
			String total_fee, String pay_chnl_seq, String refund_fee,
			String currency, String expand_json) throws IOException {
		return this.barcode_V0_0_1(pay_ssn_id, order_id, total_fee, pay_chnl_seq, refund_fee, currency, expand_json);
	}
}